/*
 * CmdManager.cpp
 *
 *  Created on: 23.10.2011
 *      Author: niea
 */

#include <iostream>

#include "CmdManager.h"
#include "constants.h"

CmdManager::CmdManager() {
	m_chat_client.assignSocket(&m_ssl_socket);
	m_chat_client.setName("Niea");
	m_chat_client.setPort(CONST_PORT);

	m_cmd_list.push_back(std::make_pair("name <name>", "Set user name."));
	m_cmd_list.push_back(
			std::make_pair("ping", "Show list of all available servers."));
	m_cmd_list.push_back(std::make_pair("list", "Show all users in chat."));
	m_cmd_list.push_back(std::make_pair("history", "Show all mesages in chat"));
	m_cmd_list.push_back(
			std::make_pair("connect <server IP>",
					"Connect to specified server."));
	m_cmd_list.push_back(
			std::make_pair("send <message>", "Send message to chat."));
	m_cmd_list.push_back(std::make_pair("help", "Show this help."));
	m_cmd_list.push_back(
			std::make_pair("disconnect", "Disconnect from server."));
	m_cmd_list.push_back(std::make_pair("exit", "exit from program"));
}

CmdManager::~CmdManager() {
}

int CmdManager::mainLoop() {
	printCmdList();

	while (1) {
		std::cout << ">";
		std::pair<std::string, std::string> command = readCmd();
		if (command.first == "exit") {
			m_chat_client.disconnect();
			return 0;
		} else if (command.first == "help") {
			printCmdList();
		} else if (command.first == "connect") {
			m_chat_client.connect(command.second);
		} else if (command.first == "disconnect") {
			m_chat_client.disconnect();
		} else if (command.first == "ping") {
			m_chat_client.pingServers();
		} else if (command.first == "send") {
			m_chat_client.sendMessage(command.second);
		} else if (command.first == "name") {
			m_chat_client.setName(command.second);
		} else if (command.first == "list") {
			m_chat_client.listClients();
		} else if (command.first == "history") {
			m_chat_client.showHistory();
		} else {
			std::cout << "unknown command" << std::endl;
		}
	}
}

void CmdManager::printCmdList() const {
	std::cout << std::endl << "Command list:" << std::endl;
	std::vector<std::pair<std::string, std::string> >::const_iterator it =
			m_cmd_list.begin();
	for (; it != m_cmd_list.end(); ++it) {
		std::cout << it->first << " - " << it->second << std::endl;
	}
}

std::pair<std::string, std::string> CmdManager::readCmd() {
	std::string input;
	getline(std::cin, input);

	std::string cmd = input;
	std::string param;

	int separator_pos = cmd.find(' ');
	if (separator_pos > 0) {
		cmd.erase(separator_pos, cmd.size() - separator_pos);
		param = input;
		param.erase(0, separator_pos + 1);
	}

	return std::make_pair(cmd, param);
}

void CmdManager::onSignal() {
	m_chat_client.disconnect();
}

